//
//  HZHomeCellVm.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/20.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD


class HZHomeCellVm: NSObject {
    
    
    //定义 VIP图片和转发微博属性
    var forwardText:String?
    var vipImg:UIImage?
    
    
    //定义微博的富文本内容
    var ownAttributedStrinng:NSAttributedString?
    var otherAttributedStrinng:NSAttributedString?
    
    //根据配图的数量算出配图区域的尺寸
    var imgSize:CGSize = CGSizeZero
    var otherSize:CGSize = CGSizeZero
    
 
    //定义一行配图时的尺寸
    var oneOtherImgSize:CGSize?
    var oneImgSize:CGSize?
    
    //定义一个变量记录转换之后的时间
    var rightTime:String? {
        
        //get方法及时刷新时间
        return giveTime()
    }
    
    
    //定义一个模型变量
    var cellModel:HZHomeModel? {
        
        
        
        didSet{
            
            //如果有转发微博
            if let other = cellModel?.retweeted_status {
                
                //如果转发微博里有文本和姓名
                if let name = other.user?.name ,content = other.text {
                    
                    //拼接和赋值
                    self.forwardText = "@\(name):\(content)"
                    
                }
                
            }
            
            //设置 vip 的不同图片
            setvipImg(cellModel!)
            
            //修改来着哪里的信息
            setSource()
            
            //算出图片区域的尺寸
            imgSize = giveImgSize(cellModel?.pic_urls)
            otherSize = giveImgSize(cellModel?.retweeted_status?.pic_urls)
            
            //拼接微博的富文本
            ownAttributedStrinng = getAttriText(cellModel?.text ?? "")
            otherAttributedStrinng = getAttriText(forwardText ?? "")
            
        }
    }
    
    
    private func getAttriText(text:String) -> NSAttributedString {
        
        //用获取原生的富文本 
        let attributeString = NSMutableAttributedString(string: text)
        
        //定义一个可变的模型数组
        var resultArray = [HZResultModel]()
        
        
        //匹配出整个字符串中的表情字符串
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            
            //转模型
            let result = HZResultModel(captureString: captureString.memory!, range: captureRange.memory)
            
            //添加到可变数组中去
            resultArray.append(result)
        }
        
        //为了防止越界,我们要倒着遍历把字符串转换成图片表情
        for value in resultArray.reverse() {
            
            //通过表情字符串找到对应的表情模型
            if let model = HZEmotionVM.sharedEmotion.emotionWithChs(value.captureString as String) {
                
                
                 //通过表情模型生成表情图片的富文本
                let img = UIImage(named: "\(model.pathString ?? "")/\(model.png ?? "")", inBundle: HZEmotionVM.sharedEmotion.getBundle(), compatibleWithTraitCollection: nil)
                
                let font = UIFont.systemFontOfSize(15)
                
                
                //设置富文本中显示图片
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(img, contentMode: UIViewContentMode.ScaleAspectFill, attachmentSize: CGSizeMake(font.lineHeight, font.lineHeight), alignToFont: font, alignment: YYTextVerticalAlignment.Center)

//                //初始化文字附件
//                let attachment = HZTextAttachment()
//                attachment.image = img
//                let font = UIFont.systemFontOfSize(15)
//                // 设置文字附件的大小
//                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
//                
//                // 利用图片附件初始化一个富文本
//                let attr = NSAttributedString(attachment: attachment)
//                
                //    并且把对应位置的表情文字给替换掉
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)
                
            }
            
        }
        
        // 添加特殊字符文字颜色
        // 话题
        addLinkColor("#[^#]+#", attributeString: attributeString)
        // @
        addLinkColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributeString: attributeString)
        // url
        addLinkColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributeString: attributeString)
        
        
        
        return attributeString
    }
    
    /// 添加特殊字符的颜色
    func addLinkColor(regex: String, attributeString: NSMutableAttributedString){
        
        // 话题？？ #asdfa#
        (attributeString.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
            
            
            // 设置特殊字符的文字颜色
//            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
            
                let str = (captureString.memory! as String)
//            
            //文字高亮并点击有背景和弹出弹窗
            attributeString.yy_setTextHighlightRange(captureRange.memory, color: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), backgroundColor: UIColor.orangeColor(), tapAction: { (_, att, range, rect) -> Void in
                
                    //闭包里不能用指针
//                 let str = (captureString.memory! as String)
                
//                SVProgressHUD.showInfoWithStatus("123")
                
                SVProgressHUD.showInfoWithStatus(str)
            })
        }
        
    
    }
    
    
    //计算出时间
    private func giveTime() ->String{
        
//        print(cellModel?.created_at)
        
        //"Sat Apr 23 20:08:39 +0800 2016"
        
        //获取当前
        let nowTime = NSDate()
  
        
        let formatter = NSDateFormatter()
        
        formatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        //2016-04-23 12:08:39 +0000
        
        //获取系统给的时间
        let netTime = formatter.dateFromString(cellModel!.created_at!) ?? NSDate()
        
        //获取当前时间的日历牌对象
        let calendar = NSCalendar.currentCalendar()
        
        
        //如果是今年
        if isYearOrNot(netTime) {
            
            //如果是今天
            if calendar.isDateInToday(netTime) {
                
                
                //计算出当前时间和系统给的时间的时间差,以秒为单位
                let timeMag = nowTime.timeIntervalSinceDate(netTime)
                
                //如果是1分钟之内
                if timeMag <= 60 {
                    
                    return "刚刚"
                    
                }else if timeMag <= 3600 {
                    //如果是1小时之内
                    return "\(Int(timeMag/60))分钟前"
                    
                } else {
                    //如果是1天之内
                     return "\(Int(timeMag/3600))小时前"
                    
                }
                
                
                
            } else if calendar.isDateInYesterday(netTime){
                //如果是昨天
                formatter.dateFormat = "HH:mm:ss"
                
                return "昨天\(formatter.stringFromDate(netTime))"
                
                
            } else {
                //如果是其他天数
                formatter.dateFormat = "MM-dd HH:mm"
                

                
                return "\(formatter.stringFromDate(netTime))"
            }
            
            
            
            
        }else {
            //如果不是今年
            //如果是其他天数
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            
            
            return "\(formatter.stringFromDate(netTime))"
            
        }
        
        
    }
    
    
    //判断是否是今年
    private func isYearOrNot(netTime: NSDate)->Bool{
        
        
            let formatter = NSDateFormatter()
        
        //设置只有年份的时间格式
        formatter.dateFormat = "yyyy"
        
        
        let nettime = formatter.stringFromDate(netTime)
        
        let nowTime = formatter.stringFromDate(NSDate())
    
        
        
        return (nettime == nowTime)
        
    }
    
    
    
    
    
      //获取一张视图的尺寸
     func  giveOneSize(){

        oneImgSize = giveOneImgSize(cellModel?.pic_urls)
        oneOtherImgSize = giveOneImgSize(cellModel?.retweeted_status?.pic_urls)
        
    }
    

    
    
     private func giveOneImgSize(pic_urls:[HZImageModel]?) ->CGSize{
        
        
        //如果没有配图或者配图的数量为0,就返回CGSizeZero
        guard let urlString = pic_urls?.last?.thumbnail_pic else {
            
            return CGSizeZero
        }
        
        //如果取得了图片
        if let icon = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) {
            
            
            //获取屏幕的缩放比
            let sacle = UIScreen.mainScreen().scale
            
            //获取图片原始大小
            var size = CGSize(width: icon.size.width*sacle, height: icon.size.height*sacle)
            
            
            //如果单图的宽度小于100,就等比例缩放
            if size.width < 100 {
                
                let s = 100/size.width
                
                size.height = size.height*s
                
                size.width = 100
                
                //高度不超过150
                if size.height > 150 {
                    size.height = 150
                }
            }
            
            
            return size
        }
        
        
        return CGSizeZero
    }
    
    
    
    // MARK: -  算出图片区域的尺寸
    private func giveImgSize(pic_urls:[HZImageModel]?) ->CGSize{
        
        //如果没有配图
        guard let imgArrM = pic_urls where imgArrM.count != 0 else {
            
            
            return CGSizeZero
        }
        
        
        
        //如果有配图
        
        //计算出行和列数
        let row = (imgArrM.count != 4) ? (imgArrM.count > 3 ? 3 : imgArrM.count) : 2
        
        let column = ((imgArrM.count - 1)/3) + 1
        
        
     
        
        
        
        let w = Double(row) * itemW + HZItemMagin*Double((row-1))
        let h = Double(column) * itemW + HZItemMagin*Double((column-1))
        
        
         let size = CGSize(width: w, height: h)
        
//        print(size)
        
        return size
    }
    
    
    //修改来着哪里的信息
    private func setSource(){
        //"source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",
        
        var sou = cellModel?.source
        
        
        if let startStr = sou?.rangeOfString(">")?.endIndex , endStr = sou?.rangeOfString("</")?.startIndex{
      
        
        sou = sou?.substringWithRange(startStr..<endStr)
        
        cellModel?.source = "来着 \(sou ?? "")"
            
        }
    }
    
    
    
    // MARK: -  设置 vip图片
    private func setvipImg(cellModel:HZHomeModel){
        
        //如果没有值就直接返回
        guard let vipName = cellModel.user?.mbrank else{
            
           
 
            return
        }
        
        
        //如果没有 vip
        if vipName == 0 {
              vipImg = UIImage(named: "common_icon_membership_expired")
            return
        }
        
        if vipName > 0 && vipName < 7 {
            
            let vipString = "common_icon_membership_level\(vipName)"
            
            //        print(vipString)
            
            vipImg = UIImage(named: vipString)
            
        }
   
    }
    

}
